lobsterlayui.main(['index', 'layer', 'form', 'element', 'table', 'tree'], {
    data: {
        $layui: null,
        nodeList: [],
        treeData: [],
        seleNode: { id: 0 },
        seleClassId: 0,//选择的主症状id
        symptomClassList: [], //症状类型
        tableid: null,
        tableClassid: null,
    },
    pageload: function (right) {
        console.log(right);
        var self = this;
        this.initEvent();

        this.loadAllNode();
        this.loadClass(() => {
            self.loadClassTable();
        });
    },
    initEvent: function () {
        var self = this;
        document.addEventListener("visibilitychange", function () {
            console.log(document.visibilityState);
        });
        // 监听表头工具栏
        layui.table.on("toolbar(List)", function (obj) {
            if (obj.event == "add") {
                if (self.data.seleNode.id == 0) {
                    layer.msg("请选择部位");
                    return;
                }
                self.viewEdit(null);
            }
        });
        //监听按钮事件
        layui.table.on('tool(List)', function (obj) {
            var data = obj.data;//当前行数据
            var layEvent = obj.event;//获得lay-event的值
            switch (layEvent) {
                case 'enstatus':
                    data.DelFlag = data.DelFlag == "0" ? 1 : 0;
                    self.updateState(data);
                    break;
                case 'edit':
                    self.viewEdit(data);
                    break;
            }
        });
        layui.form.on("select(PosId)", function (data) {
            var id = $("#PosId").val();
            self.viewClassSelect(id);
            layui.form.render("select");
        })

        $("#Middle").on("click", "div[lay-id='ClassList'] .layui-table-body tr", function () {
            $("tr").removeClass("seletr");
            $(this).addClass("seletr");
            var top = $(this).offset().top;
            var left = $(this).offset().left + $(this).width() - 1;
            //$(".trnodeto").css({ top: top, left: left }).show();
            var data = layui.table.cache.ClassList[$(this).attr("data-index")];
            self.data.seleClassId = data.ClassId;
            self.loadTable(true);
        })
        $("#Middle").on("click", "td[data-field='operation'] a", function (e) {
            // e.stopPropagation();
            var layEvent = $(this).attr("lay-event");
            var data = layui.table.cache.ClassList[parseInt($(this).parents("tr").attr("data-index"))];   //行内数据 
            switch (layEvent) {
                case 'enstatus':
                    data.DelFlag = data.DelFlag == "0" ? 1 : 0;
                    self.updateSymptonClassState(data);
                    break;
                case 'edit':
                    self.viewSymptomClassEdit(data);
                    break;
            }
            return false; //阻止事件冒泡
        })


        // 监听表头工具栏
        layui.table.on("toolbar(ClassList)", function (obj) {
            if (obj.event == "add") {
                if (self.data.seleNode.id == 0) {
                    layer.msg("请选择部位");
                    return;
                }
                self.viewSymptomClassEdit(null);
            }
        });
    },
    /**
     * 加载类型及部门
     * */
    loadClass: function (func) {
        //获取数据
        lobsterlayui.GETAPI('tsAdmin.getSymptomClassList').then(retdata => {
            this.data.symptomClassList = retdata.symptomClassList;
            var deptList = retdata.deptList;
            $("#DeptCode").append("<option value=''>请选择</option>");
            deptList.forEach(item => {
                $("#DeptCode").append('<option value="' + item.DeptId + '">' + item.Name + '</option>')
            });
            func && func();
        })
    },
    loadSelectPos: function (func) {
        var list = this.data.nodeList;
        //显示部位下拉
        $("[name='PosId']").html("");
        list.forEach(item => {
            if (item.ParentId > 0)
                $("[name='PosId']").append('<option value="' + item.PositionCode + '">' + item.PositionName + '</option>');
        })
        layui.form.render("select");
        func && func();
    },
    //加载内容
    loadAllNode: function () {
        //获取数据
        var self = this;
        lobsterlayui.GETAPI('tsAdmin.getPositionList').then(retdata => {
            self.data.nodeList = retdata.positionList;
            self.initData();
        })
    },
    //重新组装成tree数据
    initData: function () {
        var root = {
            id: 0,
            type: 0,
            text: '所有部位',
            selected: true,
            children: [],
            spread: true
        };
        //var list = this.data.nodeList.filter(item => item.NodeType == 1 || item.NodeType==2);
        var list = this.data.nodeList;
        var currAdd = function (node, li) {
            var newnode = { id: node.ID, type: 2, text: node.PositionName, children: [], spread: true, selected: false }
            li.children.push(newnode)
            list.forEach(item => {
                if (item.ParentId == node.ID)
                    currAdd(item, newnode);
            })

        }
        list.forEach(item => {
            if (item.ParentId == 0)
                currAdd(item, root);
        });
        console.log(root)
        this.data.treeData = [root];
        this.viewToTree();

    },

    /**
     * 显示树
     * */
    viewToTree: function () {
        var self = this;
        //渲染
        $('#PosId2').combotree({
            data: self.data.treeData,
            onSelect: function (node) {
                self.data.seleNode = node;
                self.loadClassTable(true);
                self.loadTable(true);
                if (node.id > 0) {
                    //症状下拉列表
                    var d = self.data.nodeList.filter(a => a.ID == node.id);
                    $("#PosId").val(d[0].PositionCode);
                    self.viewClassSelect(d[0].PositionCode);
                }
            }, onLoadSuccess: function (node, data) {
                $("#PosId2").combotree('setValue', 0);
            }
        });
        //默认选择第一个
        $(".layui-tree-main:eq(0)").addClass("nodeover");
        self.loadClassTable(true);
        self.loadTable();
    }
    ,
    /**
     * 显示编辑界面
     * @param {any} data
     */
    viewEdit: function (data) {
        var self = this;

        layer.open({
            type: 1
            , title: '症状编辑'
            , btn: ['保存', "关闭"]
            , content: $('#openPosition').html()
            , area: ['800px', '90%']  //宽，高
            , cancel: function (index, layero) {
                layer.close(index);
            }
            , success: function () {
                if (!data) {
                    data = { SymId: 0, Symptom: "", ClassId: "", DelFlag: 0, ClassType: 0, SortOrder: 1, DeptCode: "" };
                }

                self.loadSelectPos(() => {
                    if (data.PositionCode)
                        $("#PosId").val(data.PositionCode);
                });
                self.viewClassSelect(data.PositionCode);
                self.loadClass(() => {
                    $("#DeptCode").val(data.DeptCode);
                    layui.form.render("select");
                });
                $("#Symptom").val(data.Symptom);
                $("#ClassId").val(data.ClassId);
                $("#ClassType").val(data.ClassType);
                layui.form.render("select");
            }
            , yes: function (index, layero) {
                data.Symptom = $("#Symptom").val();
                data.DeptCode = $("#DeptCode").val();
                data.ClassId = $("#ClassId").val();
                data.ClassType = $("#ClassType").val();
                self.save(data, () => {
                    layer.close(index);
                })
            }
        });
    },

    /**
    * 显示编辑界面
    * @param {any} data
    */
    viewSymptomClassEdit: function (data) {
        var self = this;

        layer.open({
            type: 1
            , title: '主症状编辑'
            , btn: ['保存', "关闭"]
            , content: $('#openSymptomClass').html()
            , area: ['800px', '90%']  //宽，高
            , cancel: function (index, layero) {
                layer.close(index);
            }, success: function () {
                if (!data) {
                    data = {
                        ClassId: 0, ClassCode: "", ClassName: "", ParentId: 0, PositionCode: "", ClassType: 0, DelFlag: 0, SortOrder: 1
                    };
                }
                self.loadSelectPos(() => {
                    if (data.PositionCode)
                        $("#PosId3").val(data.PositionCode);
                });

                $("#ClassName").val(data.ClassName);
                $("#ClassType2").val(data.ClassType);
                layui.form.render("select");
            }
            , yes: function (index, layero) {
                data.ClassName = $("#ClassName").val();
                data.ClassType = $("#ClassType2").val();
                data.PositionCode = $("#PosId3").val();
                self.saveSymptomClass(data, () => {
                    layer.close(index);
                })
            }
        });
    },

    /**
     * 症状类型下拉
     * */
    viewClassSelect: function (id) {

        console.log(id);
        var self = this;
        $("#ClassId").html("<option value='0'>请选择</option>");
        self.data.symptomClassList.forEach(item => {
            if (item.PositionCode == id) {
                $("#ClassId").append('<option value="' + item.ClassId + '">' + item.ClassName + '(' + self.getClassTypeText(item.ClassType) + ')</option>')
            }
        })

    },
    /**
     * 
     * 获取适应人群类型
     * @param {any} d
     */
    getClassTypeText: function (d) {
        var str = "";
        if ((d & 1) == 1) str += "男,";
        if ((d & 2) == 2) str += "女,";
        if (str) return str.substr(0, str.length - 1);
        return "";
    },

    /**
     * 保存
     * */
    save: function (data, success) {
        if (!data.Symptom || !data.DeptCode || data.ClassId == 0) {
            layer.msg("请完善信息");
            return;
        }
        var self = this;
        console.log(data);
        lobsterlayui.POSTAPI('tsAdmin.saveSymptom', data).then(retdata => {
            layer.msg("操作成功");
            self.loadTable();
            success && success();
        })
    },
    /**
     * 修改状态
     * */
    updateState: function (data) {
        var self = this;
        lobsterlayui.GETAPI('tsAdmin.updateSymptomState', { id: data.SymId, status: data.DelFlag }).then(retdata => {
            layer.msg("操作成功");
            self.loadTable();
        }).catch(res => {
            layer.msg(res.msg);
        })
    },
    /**
    * 保存
    * */
    saveSymptomClass: function (data, success) {
        if (!data.ClassName || data.ClassType == 0 || !data.PositionCode) {
            layer.msg("请完善信息");
            return;
        }
        console.log(data);
        var self = this;
        lobsterlayui.POSTAPI('tsAdmin.saveSymptomClass', data).then(retdata => {
            layer.msg("操作成功");
            // self.loadClass(() => { self.loadClassTable() });
            success && success();
        }).catch(res => {
            layer.msg(res.msg);
        })
    },
    /**
     * 修改状态
     * */
    updateSymptonClassState: function (data) {
        var self = this;
        lobsterlayui.GETAPI('tsAdmin.updateSymptomClassState', { ClassId: data.ClassId, status: data.DelFlag }).then(retdata => {
            layer.msg("操作成功");
            // self.loadClass(() => { self.loadClassTable() });
            success && success();
        }).catch(res => {
            layer.msg(res.msg);
        })
    },
    /**
     * 加载主症状
     * */
    loadClassTable: function (bl) {
        //$(".trnodeto").hide();
        var self = this;
        var data = {};
        //症状下拉列表
        if (this.data.seleNode.id == 0) {
            data = this.data.symptomClassList;
        } else {
            var d = this.data.nodeList.filter(a => a.ID == this.data.seleNode.id || a.ParentId == this.data.seleNode.id);
            data = this.data.symptomClassList.filter(a => d.filter(b => b.PositionCode == a.PositionCode).length > 0);
        }
        if (bl && data.length > 0) {
            this.data.seleClassId = data[0].ClassId;
        }
        if (data.length == 0) {
            this.data.seleClassId = 0;
        }
        if (this.data.tableClassid && !bl) {

            this.data.tableClassid.reload({
                data: data
            });
            return;
        }
        console.log(this.data.seleNode.id);
        this.data.tableClassid = layui.table.render({
            elem: "#ClassList",
            headers: lobsterlayui.GetHeaderData(),
            toolbar: '#classadd',
            height: 'full-90',
            data: data,
            limit: '1000',
            cols: [[
                { field: 'ClassName', title: '主症状' },
                { field: 'ClassType', title: '适用人群', templet: "#classTypeTemp", width: 100 },
                { field: 'DelFlag', title: '状态', align: 'center', templet: "#statusTemp", width: 80 },
                { field: 'operation', title: '操作', toolbar: '#operation', width: 150, fixed: "right" }
            ]],
            done: res => {
                console.log(self.data.seleClassId);
                //默认选中
                for (var i = 0; i < res.data.length; i++) {
                    if (res.data[i].ClassId == self.data.seleClassId) {
                        var tr = $(".layui-table-main tr:eq(" + i + ")");
                        var top = tr.offset().top;
                        var left = tr.offset().left + tr.width() - 1;
                        $(".layui-table-main tr:eq(" + i + ")").addClass("seletr");
                        //$(".trnodeto").css({ top: top, left: left }).show();
                    }
                }
            }
        });
    },
    /**
     * 加载症状表格
     * */
    loadTable: function (bl) {
        if (this.data.tableid && !bl) {
            this.data.tableid.reload();
            return;
        }
        var self = this;
        this.data.tableid = layui.table.render({
            elem: "#List",
            headers: lobsterlayui.GetHeaderData(),
            toolbar: '#baradd',
            height: 'full-20',
            url: lobsterlayui.GetLowCodeUrl('tsAdmin.getSymptomList'),
            where: {
                pid: self.data.seleNode.id,
                classId: self.data.seleClassId
            },
            limit: '100',
            height: 'full-90',
            page: false,
            cols: [[
                { field: 'Symptom', title: '症状' },
                { field: 'ClassType', title: '适应人群', templet: "#classTypeTemp", width: 100 },
                { field: 'DeptName', title: '推荐科室', width: 100 },
                { field: 'DelFlag', title: '状态', align: 'center', templet: "#statusTemp", width: 80 },
                { title: '操作', toolbar: '#operation', width: 150, fixed: "right" }
            ]],
            parseData: function (res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.count,
                    data: res.data.list
                }
            }
        });
    }
})